package action

import java.util
import java.util.UUID

import Utils.{JsonMaker, ProbUtil}
import beans.{LogBean, Page, UserBean}
import com.doit.utils.NginxSender
import org.apache.commons.lang3.{RandomStringUtils, RandomUtils, StringUtils}
import org.apache.log4j.Logger

import scala.collection.immutable

/**
  * Created by hunter.coder 涛哥  
  * 2019/2/11 10:56
  * 交流qq:657270652
  * Version: 1.0
  * 更多学习资料：https://blog.csdn.net/coderblack/
  * Description: 行为实体类
  **/
class ActionEntities(val u: UserBean) {


  val log: Logger = Logger.getLogger("roll")
  val sender:NginxSender = new NginxSender("")
  def startup(): Page = {

    // 启动后，即生成一个sessionid
    u.sessionId = RandomStringUtils.random(12,true,true)
    val bean = new LogBean(u,"startup",System.currentTimeMillis(),new util.HashMap[String,String]())
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))

    // 产生一个首页浏览事件
    val indexPage = new Page("001",
      "",
      "http://www.51doit.com",
      "线上多易--搞IT，就要往死里学",
      List("ad01","ad02","ad03","ad04"),
      List("act01","act02","act03","act04"))
    viewPg(List(indexPage),"")

    indexPage
  }

  // 登录
  def login(): Unit = {
    // 更新用户的账号信息
  }

  //  注册
  def regist(): Unit = {

    if (u.account.isEmpty) {
      val per = RandomUtils.nextInt(10, 50)
      if (ProbUtil.probilityDo(per)) {
        u.account = RandomStringUtils.random(6, true, true)
        // println(s"用户注册： ${u.account}")
      }
    }

    // 更新用户的账号信息，其他信息
  }

  // 广告曝光展现事件
  def showAD(curpg:Page,adids: immutable.Seq[Int]) = {
    for(id <- adids) {
      val event = new java.util.HashMap[String,String]()
      event.put("ad_id",id+"")
      event.put("pg_id",curpg.pgId)
      event.put("title",curpg.pgTitle)
      event.put("url",curpg.pgUrl)
      val bean = new LogBean(u, "ad_show", System.currentTimeMillis(), event)
      log.info(JsonMaker.toJson(bean))
      sender.send(JsonMaker.toJson(bean))
    }
  }

  // 页面浏览
  def viewPg(pgs: List[Page],preUrl:String,adtrackid:String=""): Page = {
    val index = RandomUtils.nextInt(0, pgs.size)
    val pg = pgs(index)
    // 随机生成页面上的广告id（代码限定为6种）
    val tmp = RandomUtils.nextInt(1,7)
    val adids: immutable.Seq[Int] = for(i<- 1 to tmp) yield i

    val event = new java.util.HashMap[String,String]()
    event.put("pgid",pg.pgId)
    event.put("skuid",pg.pgSkuId)
    event.put("title",pg.pgTitle)
    event.put("url",pg.pgUrl)
    event.put("referal",preUrl)
    event.put("ad_trace_id",adtrackid)

    // 一定几率标记为被推荐商品
    val isRec = RandomUtils.nextBoolean()
    event.put("is_rec",if(isRec) "1" else "0")

    // 广告展现
    showAD(pg,adids)

    // 添加广告追踪id
    event.put("ad_trace_id",adtrackid)

    val bean = new LogBean(u,"pg_view",System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))
    pg
  }

  // 搜索行为
  def search(curPage:Page): Unit = {
    val logType = "search"
    val keywords = RandomStringUtils.random(6, true, false)

    val event = new java.util.HashMap[String,String]()
    event.put("keywords",keywords)
    event.put("url",(if (curPage==null) "" else curPage.pgUrl))
    val bean = new LogBean(u,logType,System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))
  }

  //  添加购物车
  def addCart(curPage:Page,adtrackid:String=""): Unit = {
    val logType = "addcart"

    val event = new java.util.HashMap[String,String]()
    event.put("skuid",curPage.pgSkuId)
    event.put("url",curPage.pgUrl)
    event.put("ad_trace_id",adtrackid)
    val bean = new LogBean(u,logType,System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))
  }

  //  添加喜欢
  def favor(curPage:Page): Unit = {
    val logType = "favor"

    val event = new java.util.HashMap[String,String]()
    event.put("skuid",curPage.pgSkuId)
    event.put("url",curPage.pgUrl)
    val bean = new LogBean(u,logType,System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))
  }

  // 点击广告
  def clickAd(curPage:Page,pgs: Map[String,Page],adItems:Map[String,List[String]]): Unit = {
    val logType = "ad_click"
    // 获取广告id
    val i = RandomUtils.nextInt(1,curPage.pgAds.size)
    // 获取广告上的items页面id
    val items: Option[List[String]] = adItems.get(i+"")
    // 生成广告跟踪id
    val adtrackid = UUID.randomUUID().toString

    // log
    val event = new java.util.HashMap[String,String]()
    event.put("adid",curPage.pgAds(i))
    event.put("url",curPage.pgUrl)
    event.put("ad_trace_id",adtrackid)
    val bean = new LogBean(u,logType,System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))

    // 广告点击后，有一定几率点击广告页面中的商品链接
    if(!items.isEmpty && ProbUtil.probilityDo(20)){
      // 获取广告上的items页面列表
      val pgIds: List[String] = items.get
      val pgList: List[Page] = ( for (pgid <- pgIds) yield pgs.get(pgid).get ).toList

      viewPg(pgList,"",adtrackid)
    }
  }

  // 点击活动
  def clickAct(curPage: Page, pages: Map[String, Page]) = {

    val logType = "act_click"
    // 获取活动id
    val i = RandomUtils.nextInt(0,curPage.pgActs.size)

    // log
    val event = new java.util.HashMap[String,String]()
    event.put("actid",curPage.pgActs(i))
    event.put("url",curPage.pgUrl)
    val bean = new LogBean(u,logType,System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))

    // 50% 几率参与活动
    if(ProbUtil.probilityDo(50)){
      joinAct(curPage,curPage.pgActs(i),pages)
    }



  }

  // ***** 参与活动
  def joinAct(curPage: Page, actid:String,pages: Map[String, Page]) = {

    val logType = "act_join"

    // log
    val event = new java.util.HashMap[String,String]()
    event.put("actid",actid)
    event.put("url",curPage.pgUrl)
    val bean = new LogBean(u,logType,System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))


    //50% 几率完成活动注册
    regAct(curPage,actid,pages)

  }


  // *** 活动注册
  def regAct(curPage: Page, actid:String,pages: Map[String, Page]) = {

    val logType = "act_register"

    // log
    val event = new java.util.HashMap[String,String]()
    event.put("actid",actid)
    event.put("channel","ch"+RandomUtils.nextInt(10,20))
    event.put("url",curPage.pgUrl)
    val bean = new LogBean(u,logType,System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))

  }


  // 提交订单
  def subOrder(curPage: Page, pages: Map[String, Page]) = {

    val logType = "order_sub"


    var skuList = List[(String,Int)]()
    for(i<- 1 to RandomUtils.nextInt(2,6)){
      // 生成若干个商品
      skuList:+=((RandomUtils.nextInt(200,500)+"",RandomUtils.nextInt(1,5)))
    }

    // log
    val event = new java.util.HashMap[String,String]()
    val orderId = RandomUtils.nextInt(10000,80000);
    event.put("order_id","od"+orderId)
    event.put("goods",skuList.mkString(","))
    val bean = new LogBean(u,logType,System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))


    // 提交订单后，80%概率支付订单
    if(ProbUtil.probilityDo(80)) {
      payOrder(orderId, skuList)
    }

  }


  // *** 支付订单
  def payOrder(orderId:Int,skuList:List[(String,Int)]) = {

    val logType = "order_pay"


    val totalAmount = RandomUtils.nextInt(1000,5000)

    // log
    val event = new java.util.HashMap[String,String]()
    event.put("order_id","od"+orderId)
    event.put("total_money",totalAmount+"")
    event.put("goods",skuList.mkString(","))
    val bean = new LogBean(u,logType,System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))

  }




  //  点赞
  def thumbup(curPage:Page): Unit = {
    val logType = "thumbup"

    // log
    val event = new java.util.HashMap[String,String]()
    event.put("skuid",curPage.pgSkuId)
    event.put("url",curPage.pgUrl)
    val bean = new LogBean(u,logType,System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))
  }

  // 评分
  def rate(curPage:Page, isThumbup: Boolean): Unit = {
    val logType = "rate"

    var low = 0
    if (isThumbup) low = 5
    val rt = RandomUtils.nextInt(low, 11)  // 0-10分

    // log
    val event = new java.util.HashMap[String,String]()
    event.put("skuid",curPage.pgSkuId)
    event.put("rate",rt.toString)
    event.put("url",curPage.pgUrl)
    val bean = new LogBean(u,logType,System.currentTimeMillis(),event)
    log.info(JsonMaker.toJson(bean))
    sender.send(JsonMaker.toJson(bean))
  }


}
